/*
 * Copyright (c) 2023 Cshoo Org. All Rights Reserved.
 */

package org.cshoo.tattoo.embed.infra.interceptor;

import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.cshoo.tattoo.embed.infra.entity.User;
import org.cshoo.tattoo.embed.infra.utils.UserUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * @author 杨翼
 * @since 1.0
 */
@Slf4j
@Component
public class UserHandlerInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        String userHeader = request.getHeader("user");
        if (Objects.nonNull(userHeader)) {
            User user = new Gson().fromJson(userHeader, User.class);
            UserUtils.setUser(user);
        }
        return true;
    }

}
